package edu.rakovic.elearning.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;

import edu.rakovic.elearning.interfaces.User;
import edu.rakovic.elearning.service.Users;
import edu.rakovic.elearning.util.Security;

public class Login {
	
	@Property
	private String userName;
	
	@Property
    private String password;
    
	// We must have access to all users..."database"
	@Inject
	@Property
	private Users users;

	// For (single) user that is trying to login
	@SessionState
	@Property
    private User user;
	
	// required for validation
	@Component
	private Form loginForm;
	//for recordError messages
	@Inject
	private Messages messages;

	//validate loginForm
	void onValidateForm(){
		User authenticatedUser = Security.authenticate(userName, password, users);
		if (authenticatedUser != null){
			user = authenticatedUser;
		}else{
			loginForm.recordError(messages.get("authentication-failed"));
		}
	}
	
	//this happens after 
	Object onSuccess()
	{
		return Index.class;
	}
	
//	//This happens when u click on "login"
//	Object onSubmitFromLoginForm(){
//		
//		User authenticatedUser = Security.authenticate(userName, password, users);
//		if (authenticatedUser != null){
//			user = authenticatedUser;
//			return Index.class;
//		} else return Registration.class;
//		
//	}
//
	
  }
